<template>
  <view class="container">
    <!-- 蓝牙滚动列表 -->
    <scroll-view
      scroll-y
      :style="'width:690rpx;height:' + list_height + 'rpx'"
    >
      <block
        v-for="(item, index) in devicesList"
        :key="index"
      >
        <view
          class="list-item"
          :id="item.deviceId"
          @tap="Connect"
        >
          <view class="device_list">
            <text class="device_name">设备名称: {{ item.name }}</text>
            <text class="device_id">设备ID: {{ item.deviceId }}</text>
            <text class="device_rssi">信号强度RSSI: {{ item.RSSI }}</text>
          </view>
          <image
            class="device_img"
            mode="aspectFit"
            src="/static/images/bluetooth.png"
          ></image>
        </view>
      </block>
    </scroll-view>
    <!-- 搜索蓝牙的按钮 -->
    <button
      type="primary"
      class="button"
      :loading="searching"
      @tap="Search"
    >
      {{ searching ? '搜索中...' : '搜索蓝牙设备' }}
    </button>
  </view>
</template>
​
<script>
  const app = getApp()
  export default {
    data() {
      return {
        searching: false,
        devicesList: [],
        list_height: '',
      }
    },
    onLoad: function (options) {
      var that = this
      var list_height =
        (app.globalData.SystemInfo.windowHeight - 50) *
          (750 / app.globalData.SystemInfo.windowWidth) -
        60
      that.list_height = list_height
      //监听蓝牙适配器状态变化事件
      uni.onBluetoothAdapterStateChange(function (res) {
        //是否正在搜索
        that.searching = res.discovering
        if (!res.available) {
          that.searching = false
        }
      })
      //监听搜索新的设备
      uni.onBluetoothDeviceFound(function (devices) {
        //剔除重复设备，兼容不同设备API的不同返回值
        var isnotexist = true
        if (devices.deviceId) {
          if (devices.advertisData) {
            devices.advertisData = app.globalData.buf2hex(devices.advertisData)
          } else {
            devices.advertisData = ''
          }
          console.log('打印返回的蓝牙列表', devices)
          for (var i = 0; i < that.devicesList.length; i++) {
            if (devices.deviceId == that.devicesList[i].deviceId) {
              isnotexist = false
            }
          }
          if (isnotexist) {
            that.devicesList.push(devices)
          }
        } else if (devices.devices) {
          if (devices.devices[0].advertisData) {
            devices.devices[0].advertisData = app.globalData.buf2hex(
              devices.devices[0].advertisData
            )
          } else {
            devices.devices[0].advertisData = ''
          }

          console.log('打印返回的蓝牙列表', devices.devices[0])
          for (var i = 0; i < that.devicesList.length; i++) {
            if (devices.devices[0].deviceId == that.devicesList[i].deviceId) {
              isnotexist = false
            }
          }

          if (isnotexist) {
            that.devicesList.push(devices.devices[0])
          }
        } else if (devices[0]) {
          if (devices[0].advertisData) {
            devices[0].advertisData = app.globalData.buf2hex(
              devices[0].advertisData
            )
          } else {
            devices[0].advertisData = ''
          }

          console.log(devices[0])
          for (var i = 0; i < devices_list.length; i++) {
            if (devices[0].deviceId == that.devicesList[i].deviceId) {
              isnotexist = false
            }
          }

          if (isnotexist) {
            that.devicesList.push(devices[0])
          }
        }
        that.devicesList = that.devicesList
        console.log('打印返回的蓝牙列表', devices)
        console.log('打印返回的蓝牙列表2', that.devicesList)
      })
    },
    onHide: function () {
      //退出此界面是停止搜索
      var that = this
      that.devicesList = []
      if (this.searching) {
        uni.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log(res)
            that.searching = false
          },
        })
      }
    },
    methods: {
      //搜索蓝牙
      Search: function () {
        var that = this
        if (!that.searching) {
          //如果在搜索中关闭蓝牙模块
          uni.closeBluetoothAdapter({
            complete: function (res) {
              console.log(res)
              //初始化蓝牙
              uni.openBluetoothAdapter({
                success: function (res) {
                  console.log(res)
                  //获取蓝牙适配器状态
                  uni.getBluetoothAdapterState({
                    success: function (res) {
                      console.log(res)
                    },
                  })
                  //开始搜索附近蓝牙
                  uni.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: false,
                    success: function (res) {
                      console.log(res)
                      uni.stopPullDownRefresh()
                      that.searching = true
                      that.devicesList = []
                    },
                  })
                },
                fail: function (res) {
                  console.log(res)
                  uni.showModal({
                    title: '提示',
                    content: '请检查手机蓝牙是否打开',
                    showCancel: false,
                    success: function (res) {
                      that.searching = false
                      uni.stopPullDownRefresh()
                    },
                  })
                },
              })
            },
          })
        } else {
          //停止搜索附近蓝牙
          uni.stopBluetoothDevicesDiscovery({
            success: function (res) {
              console.log(res)
              that.searching = false
              uni.stopPullDownRefresh()
            },
          })
        }
      },
      //链接蓝牙的设备
      Connect: function (e) {
        var that = this
        var advertisData, name
        console.log(e.currentTarget.id)

        for (var i = 0; i < that.devicesList.length; i++) {
          if (e.currentTarget.id == that.devicesList[i].deviceId) {
            name = that.devicesList[i].name
            advertisData = that.devicesList[i].advertisData
          }
        }

        uni.stopBluetoothDevicesDiscovery({
          success: function (res) {
            console.log(res)
            that.searching = false
          },
        })
        uni.showLoading({
          title: '连接蓝牙设备中...',
        })
        uni.createBLEConnection({
          deviceId: e.currentTarget.id,
          success: function (res) {
            console.log(res)
            uni.hideLoading()
            uni.showToast({
              title: '连接成功',
              icon: 'success',
              duration: 1000,
            })
            // 并且跳进页面去
            uni.navigateTo({
              url:
                '../mqttBluetoothAdapter/device/device?connectedDeviceId=' +
                e.currentTarget.id +
                '&name=' +
                name,
            })
          },
          fail: function (res) {
            console.log(res)
            uni.hideLoading()
            uni.showModal({
              title: '提示',
              content: '连接失败',
              showCancel: false,
            })
          },
        })
      },
    },
    //下拉刷新
    onPullDownRefresh() {
      this.Search()
    },
  }
</script>
​
<style>
  page {
    background-color: #f8f8f8;
  }
  .container {
    padding: 0 30rpx 0 30rpx;
    align-items: center;
  }
  .list-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 10px 0 10px 0;
    box-sizing: border-box;
    border: 1px solid #000;
    border-style: none none solid none;
    border-bottom-color: lightgray;
  }
  .list-item:last-child {
    border-style: none;
  }
  .button {
    position: fixed;
    width: 690rpx;
    bottom: 30rpx;
  }
  .device_list {
    display: flex;
    flex-direction: column;
    width: 80%;
  }
  .device_name {
    font-size: medium;
    word-break: break-all;
  }
  .device_id {
    font-size: x-small;
    color: gray;
    word-break: break-all;
  }
  .device_rssi {
    font-size: x-small;
    color: gray;
    word-break: break-all;
  }
  .device_img {
    width: 36px;
    height: 36px;
  }
</style>
